import type { RcFile } from 'antd/lib/upload/interface';

import { UploadFileSuffix } from '@/enumTypes/upload';
import { bytesToSize, getPreviewIconUrl } from '@/utils/util';
import type { Base64FileObj } from './type';

/**
 * 文件对象(blob对象)转换base64数据文件对象
 * @param {RcFile} file 文件对象
 * @returns { Promise<Base64FileObj> }
 */
export const fileToBase64FileObj = (file: RcFile): Promise<Base64FileObj> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () =>
      resolve({
        uid: file.uid,
        fullName: file.name,
        size: file.size,
        type: file.type,
        lastModified: file.lastModified,
        lastModifiedDate: file.lastModifiedDate,
        name: file.name.slice(0, file.name.lastIndexOf('.')),
        suffix: file.name.slice(file.name.lastIndexOf('.')),
        base64Data: reader.result as string,
        fullSize: bytesToSize(file.size),
        previewIconUrl: getPreviewIconUrl(
          file.name.slice(file.name.lastIndexOf('.')) as UploadFileSuffix,
          reader.result as string
        )
      });
    reader.onerror = error => reject(error);
  });
